package com.gopay.cron.web.controller;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.gopay.cron.service.cloud.EShopAccountGenFtpFileService;
import com.gopay.cron.thread.CloudGenFileThread;

/** 
 * @ClassName: EShopFileGenController 
 * @Description: E商通手动生成某一天对账文件
 *  输入的地址格式 http://localhost:8080/此项目名称/eshop/index.shtml?date=想要生成的日期(yyyy-MM-dd)
 * @author liuxuyang
 * @date 2018年3月29日 下午3:16:13  
 */

@Controller
public class EShopFileGenController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("#{webProperties['cloud.accountGenFtp.custIds']}")
    private String custIds;

    @Value("#{webProperties['cloud.accountGenFtp.basePath']}")
    private String basePath;
    
    @Resource(name = "eShopAccountGenFtpFileService")
    private EShopAccountGenFtpFileService eShopAccountGenFtpFileService;
    
	@RequestMapping("/eshop/index")
    public void index() {
		String date = getRequest().getParameter("date");
		Set<String> custIdSet = getPlatformCustIds();
		
		/*logger.info("手动开始生成E商通对账文件...");
    	
        try {
        	//掌合的商户IDs
        	eShopAccountGenFtpFileService.genFile(basePath, date,custIdSet);
        } catch(Exception e) {
        	logger.error("手动生成E商通对账文件失败...",e);
        }
        
        logger.info("手动生成E商通对账文件结束...");*/
		new Thread(new CloudGenFileThread(eShopAccountGenFtpFileService,basePath, date,custIdSet)).start();
	}
	
	private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
	
	private Set<String> getPlatformCustIds() {
        Set<String> set = new HashSet<>();
        if(this.custIds != null && StringUtils.isNotBlank(this.custIds)) {
            if(this.custIds.contains(",")) {
                String[] strArr = this.custIds.split(",");
                for(int i = 0; i < strArr.length; i++) {
                    set.add(strArr[i]);
                }
            } else {
                set.add(this.custIds);
            }
        }
        return set;
    }
}
